package com.ghbank.rdws.common.command;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Map;


import com.ghbank.rdws.common.utils.StringSubstitutorUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ShellExecutor {
    private static final String PLACEHOLDER_PREFIX = "${";
    private static final String PLACEHOLDER_SUFFIX = "}";
    
    public static int execute(String name,Map<String,Object> params) throws Exception {
        String command = StringSubstitutorUtils.replace(name, params, PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, false);
        String[] commands = command.split(" ");
        String commandFile = commands[0];
        int result = -1;
        File file = new File(commandFile);
        if (!file.exists()) {
            throw new Exception("脚本文件不存在，请检查脚本路径：" + commandFile);
        } else {
            try {
                //String[] command = new String[] { commandFile };
                ProcessBuilder builder = new ProcessBuilder(commands);
                builder.directory(new File(file.getParent()));
                builder.redirectErrorStream(true);
                Process process = builder.start();
                log.info("正执行脚本: " + command);
                process.waitFor();
                result = process.exitValue();
                if (result == 0) {
                    log.info("脚本执行完成，执行返回状态：" + result);
                } else {
                    process.destroy();
                    throw new Exception("脚本执行异常，执行返回状态：" + result);
                }
                process.destroy();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                throw e;
            }
        }
        return result;
    }
    
    public static String execute(String command) {
        StringBuffer result = new StringBuffer();
        try {
            Process process = Runtime.getRuntime().exec(new String[] { "sh", "-c", command});
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                line = line.trim();
                result.append(line).append("<br/>");
            }
            bufferedReader.close();
            process.destroy();
            log.info("命令执行成功");
        } catch (Exception e) {
            log.error("命令{}执行失败",command);
            throw new RuntimeException("命令执行失败", e);
        }
        return result.toString();

    }
}
